package com.suyang.syt.listener;

import java.io.PrintWriter;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.suyang.syt.model.User;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.MySessionContext;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.JsonUtil;

@SuppressWarnings("unchecked")
public class AuthInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = null;
		String sessionID = request.getParameter("sessionID");
		if (EmptyUtil.isNotEmpty(sessionID)) {
			// 通过uploadify上传文件请求
			session = MySessionContext.getSession(sessionID);
		} else {
			session = request.getSession();
		}
		HandlerMethod hm = (HandlerMethod) handler;
		User user = (User) session.getAttribute("loginUser");
		if (user == null) {
			return false;
		} else {
			boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
			if (!isAdmin) {
				// 不是超级管理人员，就需要判断是否有权限访问某些功能
				Set<String> actions = (Set<String>) session.getAttribute("allActions");
				String className = hm.getBean().getClass().getName();
				int flag = className.indexOf("$$");
				if (flag != -1) {
					className = className.substring(0, flag);
				}
				String methdName = hm.getMethod().getName();
				String aname = className + "." + methdName;
				if (actions.contains(aname)) {
					return true;
				}
				PrintWriter out = response.getWriter();
				if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
					// 处理异步AJAX请求
					AjaxObj ajaxObj = new AjaxObj(0, "您没有访问此功能的权限！");
					out.write(JsonUtil.toJson(ajaxObj));
					out.flush();
					out.close();
				} else {
					// 处理其他请求
					response.setContentType("text/html;charset=utf-8");
					response.setCharacterEncoding("UTF-8");
					String path = request.getContextPath() + "/admin/index";
					out.write("<script type='text/javascript'>alert('您没有访问此功能的权限！'); window.top.location.href='" + path + "';</script>");
					out.flush();
					out.close();
				}
				return false;
			}
		}
		return super.preHandle(request, response, handler);
	}
}